package com.mc.fastkit.view.host

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.widget.FrameLayout
import android.widget.HorizontalScrollView
import com.mc.fastkit.ext.cast
import kotlin.math.abs
import androidx.viewpager2.widget.ViewPager2

/**
 * [ViewPager2]嵌套[HorizontalScrollView]时的滑动解决方案
 * @author: MasterChan
 * @date: 2024-03-11 16:21
 */
class HorizontalScrollViewHost @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) : FrameLayout(context, attrs, defStyleAttr, defStyleRes) {

    private var touchSlop = 0
    private var lastX = 0f

    private val child: HorizontalScrollView?
        get() = if (childCount > 0) getChildAt(0).cast() else null

    init {
        touchSlop = ViewConfiguration.get(context).scaledTouchSlop
    }

    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        child ?: return super.dispatchTouchEvent(event)

        if (!child!!.canScrollHorizontally(1) && !child!!.canScrollHorizontally(-1)) {
            return super.dispatchTouchEvent(event)
        }

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                lastX = event.x
                parent.requestDisallowInterceptTouchEvent(true)
            }

            MotionEvent.ACTION_MOVE -> {
                val dx = event.x - lastX
                if (abs(dx) >= touchSlop) {
                    if (dx > 0 && child!!.canScrollHorizontally(-1)) {
                        parent.requestDisallowInterceptTouchEvent(true)
                    } else if (dx < 0 && child!!.canScrollHorizontally(1)) {
                        parent.requestDisallowInterceptTouchEvent(true)
                    } else {
                        parent.requestDisallowInterceptTouchEvent(false)
                    }
                }
            }
        }
        return super.dispatchTouchEvent(event)
    }
}